#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import time
from PyQt6.QtWidgets import (QApplication, QMainWindow, QWidget, QVBoxLayout,
                           QHBoxLayout, QPushButton, QLabel, QListWidget,
                           QListWidgetItem, QMessageBox, QSplitter, QStackedWidget)
from PyQt6.QtCore import Qt, QMutex, QEvent

# 导入自定义模块
from account_thread import AccountThread
from account_widget import AccountWidget, _UpdateAvatarEvent
from account_manager import AccountManager

# from account_widget import AccountWidget # Redundant import removed
from logger import app_logger as logger

class MainWindow(QMainWindow):
    """主窗口"""
    def __init__(self):
        super().__init__()
        self.account_manager = AccountManager()  # 账号管理器
        # 移除config_manager实现，使用默认窗口大小
        # 头像管理功能已迁移到AccountWidget中

        self.account_widgets = {}  # 保存所有账号组件
        self.pending_login_logs = {} # 暂存新账号登录日志
        self.lock = QMutex()  # 线程锁，用于保护数据
        self.login_threads = {} # 保存登录线程实例



        self.initUI() # 初始化 UI

        # 连接头像下载信号
        # 头像下载信号处理已迁移到AccountWidget中

        # 添加已加载的账号到列表和控件字典
        for account_data in self.account_manager.get_all_accounts():
            # 使用端口作为标识符
            port = account_data.get('port')
            if port:
                self.create_account_widget(str(port), account_data)
                self.addAccountToList(str(port), account_data)

    def initUI(self):
        # GUI初始化代码，保持不变
        self.setWindowTitle("小红书自动化工具")

        # 设置默认窗口大小
        self.resize(800, 600)

        # 创建中心部件
        central_widget = QWidget()
        main_layout = QVBoxLayout()
        central_widget.setLayout(main_layout)
        self.setCentralWidget(central_widget)

        # 顶部按钮区域
        btn_layout = QHBoxLayout()
        self.add_account_btn = QPushButton("添加新账号")
        self.add_account_btn.clicked.connect(self.addAccount)

        btn_layout.addWidget(self.add_account_btn)
        btn_layout.addStretch()
        main_layout.addLayout(btn_layout)

        # 创建左右分割布局
        self.splitter = QSplitter(Qt.Orientation.Horizontal)
        main_layout.addWidget(self.splitter)

        # 左侧账号列表
        self.account_list_widget = QListWidget()
        self.account_list_widget.setMaximumWidth(200) # 限制最大宽度
        self.splitter.addWidget(self.account_list_widget)

        # 右侧账号详情区域 (使用 QStackedWidget)
        self.account_detail_stack = QStackedWidget()
        self.splitter.addWidget(self.account_detail_stack)

        # 添加占位符到 StackedWidget (索引 0)
        self.placeholder_label = QLabel("请在左侧选择一个账号")
        self.placeholder_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.account_detail_stack.addWidget(self.placeholder_label)

        # 设置 splitter 初始比例
        self.splitter.setSizes([150, 850])

        # 连接列表项选择信号
        self.account_list_widget.currentItemChanged.connect(self.displayAccountDetails)
        self.account_list_widget.itemClicked.connect(lambda item: self.displayAccountDetails(item, None))

    def create_account_widget(self, port, account_data):
        """创建账号控件"""
        if port not in self.account_widgets:
            widget = AccountWidget(port, account_data)
            # 确保账号数据有 is_logged 字段
            if 'is_logged' not in account_data:
                account_data['is_logged'] = False
            widget.delete_requested.connect(self.deleteAccount)
            self.account_widgets[port] = widget
            # 加载头像
            avatar_url = account_data.get('avatar', '')
            if avatar_url:
                # 头像下载功能已迁移到AccountWidget中
                pass
            return widget
        return self.account_widgets[port]

    # def handle_avatar_downloaded(self, port, pixmap): # Unused method removed
    #     """处理头像下载完成"""
    #     if port in self.account_widgets:
    #         widget = self.account_widgets[port]
    #         # 使用自定义事件更新头像
    #         event = _UpdateAvatarEvent(pixmap)
    #         QApplication.postEvent(widget, event)

    def addAccountToList(self, port, account_data):
        """添加账号到左侧列表"""
        nickname = account_data.get('nickname', port)
        item = QListWidgetItem(nickname)
        item.setData(Qt.ItemDataRole.UserRole, port) # 存储 port
        self.account_list_widget.addItem(item)

        # 将 AccountWidget 添加到 StackedWidget
        if port in self.account_widgets:
            widget = self.account_widgets[port]
            # 检查是否已经添加到StackedWidget
            already_added = False
            for i in range(self.account_detail_stack.count()):
                if self.account_detail_stack.widget(i) == widget:
                    already_added = True
                    break

            # 如果没有添加过，则添加
            if not already_added:
                self.account_detail_stack.addWidget(widget)

    def displayAccountDetails(self, current_item, previous_item):
        """在右侧显示所选账号的详情"""
        if current_item:
            port = current_item.data(Qt.ItemDataRole.UserRole)

            if port in self.account_widgets:
                widget_to_display = self.account_widgets[port]

                # 确保账号数据是最新的
                account_data = self.account_manager.get_account(port)
                if account_data:
                    widget_to_display.update_account_data(account_data)

                # 确保widget已添加到StackedWidget
                already_added = False
                for i in range(self.account_detail_stack.count()):
                    if self.account_detail_stack.widget(i) == widget_to_display:
                        already_added = True
                        break

                if not already_added:
                    self.account_detail_stack.addWidget(widget_to_display)

                # 切换到对应的 widget
                self.account_detail_stack.setCurrentWidget(widget_to_display)
            else:
                # 如果找不到 widget，显示占位符
                self.account_detail_stack.setCurrentIndex(0)
        else:
            # 没有选中项，显示占位符
            self.account_detail_stack.setCurrentIndex(0)

    def addAccount(self):
        # 获取一个可用端口
        port = self.account_manager.find_available_port()
        logger.info(f"为新账号分配端口: {port}")
        # 显示登录提示
        QMessageBox.information(self, "登录提示", f"即将打开浏览器，请在浏览器中完成登录，登录成功后账号将自动添加。\n\n分配的端口号: {port}")

        # 直接打开浏览器
        try:
            # 创建并启动登录线程
            login_thread = AccountThread(str(port), port=port)
            login_thread.login_success.connect(
                lambda acc_port, user_info: self.handle_login_success(str(port), user_info)
            )
            login_thread.error_occurred.connect(
                lambda err: self.handle_login_error(str(port), err)
            )
            login_thread.start()

            # 保存线程引用
            self.login_threads[str(port)] = login_thread

        except Exception as e:
            logger.error(f"添加账号时出错: {str(e)}")
            QMessageBox.warning(self, "错误", f"添加账号时出错: {str(e)}")

    def _add_temp_account(self, port, account_data):
        item = QListWidgetItem("登录中...")
        item.setData(Qt.ItemDataRole.UserRole, port)
        self.account_list_widget.addItem(item)

    def handle_login_success(self, port, user_info):
        # 确保端口信息存在
        if 'port' not in user_info or user_info['port'] is None:
            user_info['port'] = int(port) if str(port).isdigit() else self.account_manager.find_available_port()

        # 确保必要字段存在
        user_info['is_logged'] = True

        # 确保其他必要字段存在
        if 'keywords' not in user_info:
            user_info['keywords'] = ""
        if 'replies' not in user_info:
            user_info['replies'] = ""
        if 'nickname' not in user_info or not user_info['nickname']:
            user_info['nickname'] = f"用户_{int(time.time())}"
        if 'red_id' not in user_info:
            user_info['red_id'] = ""
        if 'avatar' not in user_info:
            user_info['avatar'] = ""

        # 正式保存账号数据
        self.account_manager.add_account(user_info)

        # 创建正式账号组件
        account_widget = self.create_account_widget(str(port), user_info)

        # 添加到列表并显示
        self.addAccountToList(str(port), user_info)

        # 选中新添加的账号
        for i in range(self.account_list_widget.count()):
            item = self.account_list_widget.item(i)
            if item.data(Qt.ItemDataRole.UserRole) == str(port):
                self.account_list_widget.setCurrentItem(item)
                break

        # 清理临时状态
        self._cleanup_login_thread(str(port))

        # 显示成功消息
        QMessageBox.information(self, "登录成功", f"账号 {user_info.get('nickname')} 已成功添加！")

    def handle_login_error(self, account_id, error):
        # 清理登录线程
        self._cleanup_login_thread(account_id)
        QMessageBox.warning(self, "登录失败", error)

    def _cleanup_login_thread(self, account_id):
        """清理登录线程资源"""
        if account_id in self.login_threads:
            thread = self.login_threads[account_id]
            if thread.isRunning():
                thread.quit()
                thread.wait()
            del self.login_threads[account_id]

    def deleteAccount(self, account_id):
        """处理账号删除请求"""
        # 确认删除操作
        reply = QMessageBox.question(self, '确认删除',
                                   f'确定要删除账号 {account_id} 吗?',
                                   QMessageBox.Yes | QMessageBox.No,
                                   QMessageBox.No)

        if reply == QMessageBox.Yes:
            # 如果是port_XXX格式，提取端口号
            port = None
            if isinstance(account_id, str) and account_id.isdigit():
                try:
                    port = int(account_id)
                    logger.debug(f"端口号: {port}")
                except (ValueError, IndexError):
                    logger.warning(f"无法从{account_id}提取有效的端口号")

            # 如果成功提取了端口号，使用端口号删除账号
            if port is not None:
                self._cleanup_temp_account(port)
            else:
                self._cleanup_temp_account(account_id)

    def _cleanup_temp_account(self, account_id_or_port):
        """清理账号资源

        Args:
            account_id_or_port: 可以是账号ID（如port_9222）或端口号（如9222）
        """
        # 从账号管理器中删除
        self.account_manager.delete_account(account_id_or_port)

        # 如果是端口号，转换为账号ID格式
        account_id = account_id_or_port
        if isinstance(account_id_or_port, int) or (isinstance(account_id_or_port, str) and account_id_or_port.isdigit()):
            account_id = str(account_id_or_port)

        # 从列表中删除
        for i in range(self.account_list_widget.count()):
            item = self.account_list_widget.item(i)
            if item.data(Qt.ItemDataRole.UserRole) == account_id:
                self.account_list_widget.takeItem(i)
                break

        # 从控件字典中删除
        if account_id in self.account_widgets:
            widget = self.account_widgets[account_id]
            # 从StackedWidget中移除
            self.account_detail_stack.removeWidget(widget)
            widget.deleteLater()
            del self.account_widgets[account_id]

        # 如果列表为空，显示占位符
        if self.account_list_widget.count() == 0:
            self.account_detail_stack.setCurrentIndex(0)

    def saveAccounts(self):
        """保存账号数据到文件"""
        # 更新账号数据
        for account_id, widget in self.account_widgets.items():
            self.account_manager.update_account(account_id, widget.account_data)

        # 保存到文件
        if not self.account_manager.save_accounts():
            QMessageBox.warning(self, "保存失败", "保存账号数据失败")

    def closeEvent(self, event):
        """窗口关闭事件"""
        # 移除窗口大小保存逻辑

        # 保存账号数据
        self.saveAccounts()

        # 停止所有线程
        for account_id, widget in self.account_widgets.items():
            if hasattr(widget, 'thread') and widget.thread and widget.thread.is_running:
                widget.stop_task()

        # 等待所有线程结束
        for account_id, widget in self.account_widgets.items():
            if hasattr(widget, 'thread') and widget.thread:
                widget.thread.wait()

        event.accept()
        logger.info("应用程序已关闭")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())
